/*
 * Copyright (C) 2011 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package pl.edu.agh.ros.proxy;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.packet.Message;
import org.ros.node.DefaultNodeFactory;
import org.ros.node.Node;
import org.ros.node.NodeConfiguration;
import org.ros.node.NodeMain;
import org.ros.node.topic.Publisher;

import com.google.common.base.Preconditions;

/**
 * This is a simple rosjava {@link Publisher} {@link Node}. It assumes an
 * external roscore is already running.
 * 
 * @author ethan.rublee@gmail.com (Ethan Rublee)
 * @author damonkohler@google.com (Damon Kohler)
 */
public class ProxyTalker implements NodeMain {

	private Node node;

	@Override
	public void main(NodeConfiguration configuration) {
		Preconditions.checkState(node == null);
		Preconditions.checkNotNull(configuration);
		node = new DefaultNodeFactory().newNode("talker", configuration);
		final Publisher<org.ros.message.std_msgs.String> publisher = node.newPublisher("chatter", "std_msgs/String");
		ProxyUtils proxyUtils = new ProxyUtils();

		try {
			Connection connection = proxyUtils.connect("127.0.0.1", 5222);
			//proxyUtils.login("darek", "darek");
			connection.loginAnonymously();
			connection.getChatManager().addChatListener(new ChatManagerListener() {
				@Override
				public void chatCreated(Chat chat, boolean createdLocally) {
					if (!createdLocally) {
						chat.addMessageListener(new MessageListener() {
							@Override
							public void processMessage(Chat arg0, Message arg1) {
								if ("std_msgs/String".equals(arg1.getProperty("type"))) {
									ByteBuffer buffer = ByteBuffer.wrap((byte[]) arg1.getProperty("value"));
									buffer.order(ByteOrder.LITTLE_ENDIAN);
									try {
										org.ros.message.std_msgs.String msg = (org.ros.message.std_msgs.String) node
												.getMessageSerializationFactory()
												.newMessageDeserializer("std_msgs/String").deserialize(buffer);
										publisher.publish(msg);
									} catch (Exception e) {
										e.printStackTrace();
										System.out.println("dupaException");
									}
								}
							}

						});
					}
					;
				}
			});
			System.out.println("Server ProxyTalker running");

		} catch (Exception e) {
			if (node != null) {
				node.getLog().fatal(e);
			} else {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void shutdown() {
		node.shutdown();
		node = null;
	}

}
